<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\index\model\Unionid;
use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Application;
use think\Db;


class Login extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /*
     * 登录
     * */
    public function login()
    {
        // 获取值
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $request_array = json_decode($data_json, true);

        if (empty($request_array['code']) || empty($request_array['encryptedData']) || empty($request_array['iv'])) {
            return ['status' => '2', 'errorcode' => '200000', 'message' => '参数错误', 'result' => ''];
        }

        $code = $request_array['code'];
        $encryptedData = $request_array['encryptedData'];
        $iv = $request_array['iv'];

        $wechat_config = config('mini_program');

        $app = Factory::miniProgram($wechat_config);

        $apps = new \EasyWeChat\Work\Application($wechat_config);


        //根据code获取用户 session信息
        /***
         * Array
         * [session_key] => EYt4+b/eyjrOr775rDZ33g==
         * [openid] => o4h_s4ppuOk5vFWYNcaf1GhgyxQU
         */
        $user_data = $app->auth->session($code);
        $decryptedData = $app->encryptor->decryptData($user_data['session_key'], $iv, $encryptedData);
        $wx_openid = $user_data['openid'];   //微信openid

        // $nickname  =  $decryptedData['nickName'];  //微信昵称
        $nickname = "";  //微信昵称
        // $head_img  =  $decryptedData['avatarUrl']; //微信头像 
        $head_img = "";

        $user_mes = Db::name('user')->where(['openid' => trim($wx_openid)])->find();
        if (!empty($user_mes)) {
            //登录
            $login_type = '2'; //操作类型： 1 注册  2 登录
            $user_id = $user_mes['id'];
            if ($user_mes['status'] == 0) {
                if (isset($request_array['pid']) && $request_array['pid'] != 'undefined') {
                    $pid = $request_array['pid'];
                } else {
                    $pid = 0;
                }
                Db::name('user')->where(['openid' => trim($wx_openid)])->update(['pid' => $pid]);
            }
        } else {
            //注册
            $login_type = '1';
            if (isset($request_array['pid']) && $request_array['pid'] != 'undefined') {
                $pid = $request_array['pid'];
            } else {
                $pid = 0;
            }
            //组装数据
            $inserdate = array(
                "nickname" => $nickname,
                "avatar" => $head_img,
                "openid" => trim($wx_openid),
                'pid' => $pid,
                "createtime" => time(),
                "updatetime" => time()
            );
            $user_id = Db::name('user')->insertGetId($inserdate);
        }

        //查询用户信息
        $wx_user_mes = Db::name('user')
            ->field('id as user_id,nickname,avatar,status')
            ->where('id', $user_id)
            ->find();

        //查询该用户领取会员卡没
        $user_card = Db::name('user_card')->where(['member_id' => $wx_user_mes['user_id']])->find();
        if (!$user_card || $user_card['status'] == 2) {
            $wx_user_mes['is_vip_card'] = 0; //跳转开通页面
        } elseif ($user_card['status'] == 1) {
            $wx_user_mes['is_vip_card'] = 1; //跳转领取会员卡
        } elseif ($user_card['status'] == 0) {
            $wx_user_mes['is_vip_card'] = 2; //跳转领取会员卡
        }

        $token_model = model('Token');
        $wx_user_mes['user_token'] = $token_model->product_token($wx_user_mes['user_id'], 1);

        $this->success('登录成功', $wx_user_mes);

    }


    /*
     * 获取手机号
     * */
    public function postPhone()
    {
        // 获取值
        $data = $this->request->param('request_data');
        $data_json = base64_decode($data); //数据解密
        $request_array = json_decode($data_json, true);
        // 获取公共号config
        $config = config('mini_program');
        $encryptedData = $request_array['encryptedData'];
        $js_code = $request_array ['code'];
        $iv = $request_array ['iv'];
        // 访问url,获取内容
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $config['app_id'] . '&secret=' . $config['secret'] . '&js_code=' . $js_code . '&grant_type=authorization_code';
        $data = "";
        $data1 = "";
        $rest = file_get_contents($url, $data);

        if ($rest) {
            $recod = json_decode($rest);
            $crr['open_id'] = $recod->openid;
            // 截取-之后的保留
            $openid = substr($crr['open_id'], strripos($crr['open_id'], "-") + 0);

            $wx = new \wxBizDataCrypt\wxBizDataCrypt($config['app_id'], $recod->session_key); //微信解密函数，微信提供了php代码dome
            $errCode = $wx->decryptData($encryptedData, $iv, $data1); //微信解密函数
            if ($errCode == 0) {
                $data1 = json_decode($data1, true);
                $phoneNumber = $data1['phoneNumber'];
//                 return $phoneNumber;
                $id = Db::name('user')->where(['openid' => $openid])->value('id');
                if ($id) {
                    // 存数据
                    Db::name('user')->where('id', $id)->update(['mobile' => $phoneNumber]);
                }
                return json(['code' => 1, 'msg' => '成功', 'data' => $phoneNumber, 'time' => time()]);
            } else {
                return json(['code' => 0, 'msg' => '失败', 'data' => '', 'time' => time()]);
            }
        } else {
            return json(['code' => 0, 'msg' => '失败', 'data' => '', 'time' => time()]);
        }
    }


}